package com.jxb.image;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.BindingAdapter;

import com.jxb.permissions.JxbPermissions;

import java.io.File;
import java.util.ArrayList;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;

/**
 * @author jinxb
 * date     : 2021/8/11
 * desc     :
 */
public class PicturePicker extends FrameLayout implements BGASortableNinePhotoLayout.Delegate {
    private BGASortableNinePhotoLayout mPhotoLayout;
    private Activity mActivity;
    private int mRequestCode;
    private int maxCount;


    public PicturePicker(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.picture_picker_layout, this);
        initViews();
        initAttrs(context, attrs);
    }

    private void initViews() {
        mPhotoLayout = findViewById(R.id.photo_layout);
        mPhotoLayout.setDelegate(this);
    }

    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PicturePicker);
        //最大数量
        maxCount = typedArray.getInteger(R.styleable.PicturePicker_maxItemCount, 0);
        mPhotoLayout.setMaxItemCount(maxCount);
        //每行数量
        int itemSpanCount = typedArray.getInteger(R.styleable.PicturePicker_itemSpanCount, 1);
        mPhotoLayout.setItemSpanCount(itemSpanCount);
        //是否可以添加
        boolean plusEnable = typedArray.getBoolean(R.styleable.PicturePicker_plusEnable, false);
        mPhotoLayout.setPlusEnable(plusEnable);
    }

    public void setDelegate(BGASortableNinePhotoLayout.Delegate delegate) {
        mPhotoLayout.setDelegate(delegate);
    }

    @BindingAdapter(value = {"delegate"})
    public static void setDelegate(PicturePicker view, BGASortableNinePhotoLayout.Delegate delegate) {
        if (view != null) {
            view.setDelegate(delegate);
        }
    }

    @BindingAdapter(value = {"activity"})
    public static void setActivity(PicturePicker view, Activity activity) {
        if (view != null) {
            view.mActivity = activity;
        }
    }

    @BindingAdapter(value = {"requestCode"})
    public static void setRequestCode(PicturePicker view, int requestCode) {
        if (view != null) {
            view.mRequestCode = requestCode;
        }
    }

    @BindingAdapter(value = {"selectedPictureList"})
    public static void setSelectedPictureList(PicturePicker view, ArrayList<String> list) {
        if (view != null) {
            view.setSelectedPictureList(list);
        }
    }

    private void setSelectedPictureList(ArrayList<String> list) {
        mPhotoLayout.setData(list);
    }

    /**
     * 点击添加图片
     */
    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position,
                                        ArrayList<String> models) {
        if (mActivity == null) {
            return;
        }
        String[] permsInfo = {"相机","存储空间"};
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        JxbPermissions.requestPermissions(mActivity,permsInfo , perms, (JxbPermissions.RequestSuccessListener) () -> {
            toChoicePictureActivity();
        });
    }

    /**
     * 点击删除图片
     */
    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view,
                                           int position, String model, ArrayList<String> models) {
        mPhotoLayout.removeItem(position);
    }

    /**
     * 点击预览图片
     */
    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position,
                                     String model, ArrayList<String> models) {
        if (mActivity == null) {
            return;
        }
        String[] permsInfo = {"存储空间"};
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        JxbPermissions.requestPermissions(mActivity,permsInfo , perms, (JxbPermissions.RequestSuccessListener) () -> {
            toPreviewActivity(models,position);
        });
    }



    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition,
                                         int toPosition, ArrayList<String> models) {

    }


    /**
     * 跳转选择图片页面
     */
    private void toChoicePictureActivity() {
        if (mActivity == null) {
            return;
        }
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");
        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(getContext())
                .cameraFileDir(takePhotoDir)
                .maxChooseCount(maxCount)
                .selectedPhotos(mPhotoLayout.getData())
                .pauseOnScroll(false)
                .build();
        mActivity.startActivityForResult(photoPickerIntent, mRequestCode);
    }

    /**
     * 跳转预览页面
     */
    private void toPreviewActivity(ArrayList<String> list, int position) {
        File downloadDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerDownload");
        BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder =
                new BGAPhotoPreviewActivity.IntentBuilder(mActivity).saveImgDir(downloadDir);
        photoPreviewIntentBuilder.previewPhotos(list).currentPosition(position);
        mActivity.startActivity(photoPreviewIntentBuilder.build());
    }
}
